#!/usr/bin/perl
# 2013/11/06 Calculate moving average

use strict;
use warnings;
use IO::File;
use Getopt::Std;
use Carp qw(croak);
$| = 0;

if(@ARGV != 4 or $ARGV[0] eq '--help'){
	die "Usage : $0 -i [wig file] -w [slinding window size]\n";
}

my %chr_length = (
	'I' => 5579133,
	'II' => 4539804,
	'III' => 2452883
);



my %opt;
getopts("i:w:", \%opt);
my $FILE_in = $opt{i};
my $WINDOW = $opt{w};

my %data;
my $fh_in = IO::File->new($FILE_in) or die "cannot open $FILE_in: $!";
my $head = $fh_in->getline();
my $chr = '';
while($_ = $fh_in->getline()){
	s/\r?\n//;
	if(/variableStep chrom=(\w+) /){
		$chr = $1;
	}else{
		my ($pos, $val) = split /\t/;
		$data{$chr}{$pos} = $val;
	}
}
$fh_in->close();

print "$head";
foreach my $chr(qw(I II III)){
	print "variableStep chrom=$chr span=50\n";
	for(my $i = int($WINDOW/2); $i < $chr_length{$chr} - int($WINDOW/2); $i += 50){
		my $SUM = 0;
		my $NUM = 0;
		for(my $k = int($i - $WINDOW/2); $k <= int($i + $WINDOW/2); $k++){
			if(exists $data{$chr}{$k}){
				$SUM +=  $data{$chr}{$k};
				$NUM++;
			}
		}
		my $value = 0;
		if($NUM != 0){
			$value = $SUM / $NUM;
		}
		print "$i\t$value\n";
	}
}

